import api from './api.js';

export default {
    template: `
    <div>
        <el-table :data="cartData" style="width: 100%">
            <el-table-column prop="name" label="菜名"></el-table-column>
            <el-table-column prop="quantity" label="数量">
                <template #default="scope">
                    <el-input v-if="scope.$index === editIndex" v-model.number="scope.row.quantity" type="number" @blur="editItem(scope.$index, scope.row)"></el-input>
                    <div v-else>{{scope.row.quantity}}</div>
                </template>
            </el-table-column>
            <el-table-column prop="price" label="总价">
                <template #default="scope">
                    {{scope.row.price * scope.row.quantity}}
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="primary" @click="editIndex = scope.$index">修改</el-button>
                    <el-button type="danger" @click="deleteItem(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
            <!-- 其他列... -->
        </el-table>
        <div class="order-footer">
            <div class="total-price">总价：{{ totalPrice }}</div>
            <el-button type="primary" @click="checkout">结算</el-button>
        </div> 
    </div>                  
    `,
    props: ['userInfo', 'isLoggedIn'],
    data() {
        return {
            orderId: 0,
            cartData: [],
            editIndex: -1,
        };
    },
    async created() {
        if (this.isLoggedIn) {
            try {
                const response = await api.getOrdersByStatus(this.userInfo.id, 1);
                console.log(response.data);
                if (response.data.data != null) {
                    this.orderId = response.data.data[0].orderId;
                } else {
                    const createOrderResponse = await api.createOrder(this.userInfo.id);
                    console.log(createOrderResponse.data);
                    this.orderId = createOrderResponse.data.data.orderId;
                }
            } catch (error) {
                console.error(error);
            }
        }
        const resp = await api.getOrderDishes(this.orderId);
        let items = resp.data.data;
        console.log(items);
        for (let item of items) {
            this.cartData.push(item);
        }
    },
    methods: {
        async editItem(index, row) {
            const dishId = row.dishId;
            const dish = row;
            console.log(dish)
            console.log(dishId)
            try {
                const response = await api.updateOrderDish(this.orderId, dishId, dish.quantity);
                if (response.data.status !== 200) {
                    alert('更新订单失败');
                    throw new Error(`更新订单失败，状态码：${response.data.status}`);
                }
            } catch (error) {
                console.error(error);
            } finally {
                this.editIndex = -1; // 修改完后将editIndex设置回-1
            }
        },
        async deleteItem(index, row) {
            const dishId = row.dishId;
            try {
                const response = await api.deleteOrderDish(this.orderId, dishId);
                console.log(response.data);
                // 从购物车数据中删除
                this.cartData.splice(index, 1);
            } catch (error) {
                console.error(error);
            }
        },
        async checkout() {
            try {
                // 更新订单状态
                await api.updateOrderStatus(this.orderId, 0);
                // 清空购物车
                this.cart = [];

                api.createOrder(this.userInfo.id)
                    .then(response => {
                        console.log(response.data);
                        this.orderId = response.data.data.orderId;
                    })
                    .catch(error => {
                        console.error(error);
                    });
                this.$message.success('结算成功，购物车已清空');
            } catch (error) {
                this.$message.error('结算失败');
            }
        }
    },
    computed: {
        totalPrice() {
            return this.cartData.reduce((total, item) => total + item.quantity * item.price, 0);
        }
    },
};